package com.my.commons.utils.collections;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class IteratorIterator<V> implements Iterator<V> {
	/**
     * 1st Level iterator
     */
    private Iterator<? extends Iterable<V>> firstLevelIterator;

    /**
     * 2nd level iterator
     */
    private Iterator<V> secondLevelIterator;

    /**
     * Constructor of <tt>IteratorIterator</tt>
     *
     * @param itit an Iterator that iterate over Iterable<Value>
     */
    public IteratorIterator(Iterable<? extends Iterable<V>> itit) {
        this.firstLevelIterator = itit.iterator();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean hasNext() {
        if (secondLevelIterator != null && secondLevelIterator.hasNext())
            return true;

        while (firstLevelIterator.hasNext()) {
            Iterable<V> iterable = firstLevelIterator.next();

            if (iterable != null) {
                secondLevelIterator = iterable.iterator();

                if (secondLevelIterator.hasNext())
                    return true;
            }
        }
        return false;
    }

    /**
     * Returns next value of collection.<br>
     * If there is no next value, then {@link NoSuchElementException} thrown.
     */
    @Override
    public V next() {
        if (secondLevelIterator == null || !secondLevelIterator.hasNext())
            throw new NoSuchElementException();
        return secondLevelIterator.next();
    }

    /**
     * <font color="red"><b>NOT IMPLEMENTED</b></font>
     */
    @Override
    public void remove() {
        throw new UnsupportedOperationException("This operation is not supported.");
    }
}
